package org.example.thread4;

/**
 * Interrupt 中断线程
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/12/27 15:57
 */
public class MyThread4 extends Thread {

    private int count = 2000000;

    @Override
    public void run() {
        super.run();
        for (int i = 0; i < count; i++) {
            //判断当前线程是否已经中断，如果已经中断，则退出。也可以用：Thread.currentThread().isInterrupted() 测试线程是否中断
            if (Thread.interrupted()) {
                break;
            }
            System.out.println("[" + Thread.currentThread().getName() + "] " + i);
        }
        System.out.println("[" + Thread.currentThread().getName() + "] 运行结束.");
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread4 myThread = new MyThread4();
        myThread.start();
        int sleep = 30;
        System.out.println("[" + Thread.currentThread().getName() + "] " + sleep + " 毫秒后停止线程.");
        Thread.sleep(sleep);
        myThread.interrupt();//中断线程 myThread
        System.out.println("[" + Thread.currentThread().getName() + "] " + sleep + " 运行结束.");
    }
}
